package com.xncoding.async.config;

//import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.xncoding.async.common.mutidatesource.DSEnum;
import com.xncoding.async.common.mutidatesource.DynamicDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * MybatisPlus配置
 *
 * @author xiongneng
 * @since 2017/5/20 21:58
 */
@Configuration
@EnableTransactionManagement(order = 2)
@MapperScan(basePackages = {"com.xncoding.multisource01.common.dao.repository"})
public class MybatisPlusConfig {

    @Bean(name = "posDataSource")
    @Primary
//    @ConfigurationProperties("spring.datasource.pos")
//    public DataSource masterDataSource(DataSourceProperties properties){
    public DataSource posDataSource(Environment env){
        return DataSourceBuilder.create()
                .driverClassName(env.getProperty("spring.datasource.pos.driver-class-name"))
                .url(env.getProperty("spring.datasource.pos.url"))
                .username(env.getProperty("spring.datasource.pos.username"))
                .password(env.getProperty("spring.datasource.pos.password"))
                .build();

    }
    @Bean(name = "bizDataSource")
    public DataSource bizDataSource(Environment env){
        return DataSourceBuilder.create()
                .driverClassName(env.getProperty("spring.datasource.biz.driver-class-name"))
                .url(env.getProperty("spring.datasource.biz.url"))
                .username(env.getProperty("spring.datasource.biz.username"))
                .password(env.getProperty("spring.datasource.biz.password"))
                .build();
    }

    /**
     * 多数据源连接池配置
     */
    @Bean
    public DataSource mutiDataSource(@Autowired @Qualifier("posDataSource") DataSource posDataSource,
                                     @Autowired @Qualifier("bizDataSource") DataSource bizDataSource) {

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        HashMap<Object, Object> hashMap = new HashMap<>();
        hashMap.put(DSEnum.posDataSource, posDataSource);
        hashMap.put(DSEnum.bizDataSource, bizDataSource);
        dynamicDataSource.setTargetDataSources(hashMap);
        dynamicDataSource.setDefaultTargetDataSource(posDataSource);
        return dynamicDataSource;
    }


}
